﻿using System;
using System.Net;
using System.Web;

namespace Noix.Web
{
    public class HttpListenerWrapper : MarshalByRefObject, IDisposable
    {
        private HttpListener _listener;
        private string _virtualDir;
        private string _physicalDir;

        public void Configure(string[] prefixes, string virtualDir, string physicalDir)
        {
            _virtualDir = virtualDir;
            _physicalDir = physicalDir;
            _listener = new HttpListener();

            foreach (string prefix in prefixes)
                _listener.Prefixes.Add(prefix);
        }

        public void Start()
        {
            _listener.Start();
            _listener.AuthenticationSchemes = AuthenticationSchemes.Ntlm;
        }

        public void Stop()
        {
            _listener.Stop();
        }

        public void ProcessRequest()
        {
            HttpListenerContext ctx = _listener.GetContext();
            HttpListenerWorkerRequest workerRequest =
              new HttpListenerWorkerRequest(ctx, _virtualDir, _physicalDir);
            HttpRuntime.ProcessRequest(workerRequest);
        }

        #region IDisposable Members

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _listener.Close();
            }
        }


        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}
